<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import { NButton, NSpace, NPopconfirm, NTag, NInput, NSelect } from 'naive-ui';
import { fetchMetadataList, deleteMetadata, batchDeleteMetadata, collectMetadata, searchMetadata, type MetadataVO, type MetadataQuery } from '@/service/api/dataplatform/metadata';
import { getDataSourceList } from '@/service/api/dataplatform/datasource';
import MetadataDetailDrawer from './modules/metadata-detail-drawer.vue';
import LineageGraphModal from './modules/lineage-graph-modal.vue';
import ImpactAnalysisModal from './modules/impact-analysis-modal.vue';

const loading = ref(false);
const tableData = ref<MetadataVO[]>([]);
const selectedRowKeys = ref<number[]>([]);

// 查询参数
const queryParams = reactive<MetadataQuery & Common.PaginatingQueryRecord>({
  pageNum: 1,
  pageSize: 10,
  datasourceId: undefined,
  databaseName: '',
  tableName: '',
  tableType: undefined,
  status: undefined
});

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  onChange: (page: number) => {
    pagination.page = page;
    queryParams.pageNum = page;
    getTableData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    queryParams.pageSize = pageSize;
    queryParams.pageNum = 1;
    getTableData();
  }
});

// 数据源列表
const datasourceOptions = ref<Array<{ label: string; value: number }>>([]);

// 表类型选项
const tableTypeOptions = [
  { label: '表', value: 'TABLE' },
  { label: '视图', value: 'VIEW' }
];

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
];

// 抽屉和弹窗
const detailDrawerRef = ref<InstanceType<typeof MetadataDetailDrawer>>();
const lineageGraphModalRef = ref<InstanceType<typeof LineageGraphModal>>();
const impactAnalysisModalRef = ref<InstanceType<typeof ImpactAnalysisModal>>();

// 表格列定义
const columns = [
  { type: 'selection' },
  {
    title: '表名',
    key: 'tableName',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '数据库',
    key: 'databaseName',
    width: 150,
    ellipsis: { tooltip: true }
  },
  {
    title: '数据源',
    key: 'datasourceName',
    width: 150,
    ellipsis: { tooltip: true }
  },
  {
    title: '表类型',
    key: 'tableType',
    width: 100,
    render: (row: MetadataVO) => {
      return h(NTag, { type: row.tableType === 'TABLE' ? 'success' : 'info' }, 
        { default: () => row.tableType === 'TABLE' ? '表' : '视图' });
    }
  },
  {
    title: '表注释',
    key: 'tableComment',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '数据大小',
    key: 'dataSizeFormatted',
    width: 120
  },
  {
    title: '行数',
    key: 'rowCount',
    width: 120,
    render: (row: MetadataVO) => {
      return row.rowCount ? row.rowCount.toLocaleString() : '-';
    }
  },
  {
    title: '最后采集时间',
    key: 'lastCollectTime',
    width: 180
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    render: (row: MetadataVO) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'error' }, 
        { default: () => row.status === 1 ? '启用' : '禁用' });
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 280,
    fixed: 'right',
    render: (row: MetadataVO) => {
      return h(NSpace, null, {
        default: () => [
          h(NButton, { 
            size: 'small', 
            type: 'primary',
            onClick: () => handleViewDetail(row.id) 
          }, { default: () => '详情' }),
          h(NButton, { 
            size: 'small',
            onClick: () => handleViewLineage(row.id) 
          }, { default: () => '血缘' }),
          h(NButton, { 
            size: 'small',
            onClick: () => handleImpactAnalysis(row.id) 
          }, { default: () => '影响分析' }),
          h(NPopconfirm, {
            onPositiveClick: () => handleDelete(row.id)
          }, {
            default: () => '确定删除该元数据吗？',
            trigger: () => h(NButton, { 
              size: 'small', 
              type: 'error'
            }, { default: () => '删除' })
          })
        ]
      });
    }
  }
];

// 获取表格数据
async function getTableData() {
  loading.value = true;
  try {
    const { data } = await fetchMetadataList(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      pagination.itemCount = data.total || 0;
    }
  } finally {
    loading.value = false;
  }
}

// 加载数据源列表
async function loadDatasources() {
  const { data } = await getDataSourceList({ pageNum: 1, pageSize: 1000 });
  if (data) {
    datasourceOptions.value = (data.rows || []).map(item => ({
      label: item.name,
      value: item.id
    }));
  }
}

// 查询
function handleQuery() {
  pagination.page = 1;
  queryParams.pageNum = 1;
  getTableData();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    datasourceId: undefined,
    databaseName: '',
    tableName: '',
    tableType: undefined,
    status: undefined
  });
  pagination.page = 1;
  getTableData();
}

// 采集元数据
async function handleCollect() {
  if (!queryParams.datasourceId) {
    window.$message?.warning('请先选择数据源');
    return;
  }
  
  loading.value = true;
  try {
    const { data } = await collectMetadata(queryParams.datasourceId);
    window.$message?.success(`采集成功，共采集 ${data} 个表`);
    getTableData();
  } catch (error) {
    console.error('采集失败:', error);
  } finally {
    loading.value = false;
  }
}

// 查看详情
function handleViewDetail(id: number) {
  detailDrawerRef.value?.open(id);
}

// 查看血缘
function handleViewLineage(id: number) {
  lineageGraphModalRef.value?.open(id);
}

// 影响分析
function handleImpactAnalysis(id: number) {
  impactAnalysisModalRef.value?.open(id);
}

// 删除
async function handleDelete(id: number) {
  try {
    await deleteMetadata(id);
    window.$message?.success('删除成功');
    getTableData();
  } catch (error) {
    console.error('删除失败:', error);
  }
}

// 批量删除
async function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的数据');
    return;
  }
  
  try {
    await batchDeleteMetadata(selectedRowKeys.value);
    window.$message?.success('删除成功');
    selectedRowKeys.value = [];
    getTableData();
  } catch (error) {
    console.error('批量删除失败:', error);
  }
}

// 行选择
function handleCheck(rowKeys: number[]) {
  selectedRowKeys.value = rowKeys;
}

onMounted(() => {
  loadDatasources();
  getTableData();
});
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 查询表单 -->
    <NCard title="元数据管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NSpace>
          <NButton type="primary" @click="handleCollect">
            <icon-ic-round-refresh class="mr-4px text-16px" />
            采集元数据
          </NButton>
          <NButton type="error" :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">
            <icon-ic-round-delete class="mr-4px text-16px" />
            批量删除
          </NButton>
        </NSpace>
      </template>

      <!-- 搜索表单 -->
      <NSpace class="pb-12px" :wrap="false">
        <NSelect
          v-model:value="queryParams.datasourceId"
          placeholder="选择数据源"
          :options="datasourceOptions"
          clearable
          class="w-200px"
        />
        <NInput
          v-model:value="queryParams.databaseName"
          placeholder="数据库名"
          clearable
          class="w-200px"
        />
        <NInput
          v-model:value="queryParams.tableName"
          placeholder="表名"
          clearable
          class="w-200px"
        />
        <NSelect
          v-model:value="queryParams.tableType"
          placeholder="表类型"
          :options="tableTypeOptions"
          clearable
          class="w-150px"
        />
        <NSelect
          v-model:value="queryParams.status"
          placeholder="状态"
          :options="statusOptions"
          clearable
          class="w-150px"
        />
        <NButton type="primary" @click="handleQuery">
          <icon-ic-round-search class="mr-4px text-16px" />
          查询
        </NButton>
        <NButton @click="handleReset">
          <icon-ic-round-refresh class="mr-4px text-16px" />
          重置
        </NButton>
      </NSpace>

      <!-- 数据表格 -->
      <NDataTable
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row: MetadataVO) => row.id"
        :scroll-x="1800"
        :checked-row-keys="selectedRowKeys"
        @update:checked-row-keys="handleCheck"
        class="sm:h-full"
      />
    </NCard>

    <!-- 详情抽屉 -->
    <MetadataDetailDrawer ref="detailDrawerRef" />

    <!-- 血缘图弹窗 -->
    <LineageGraphModal ref="lineageGraphModalRef" />

    <!-- 影响分析弹窗 -->
    <ImpactAnalysisModal ref="impactAnalysisModalRef" />
  </div>
</template>

<style scoped>
.card-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
